/**
 * 2018年12月9日下午2:56:12
 * @author 谢进财
 */
package com.baihang.project.ds.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.baihang.framework.dao.Record;
import com.baihang.framework.kit.JsonKit;
import com.baihang.framework.kit.StrKit;
import com.baihang.framework.kit.database.RedisKit;
import com.baihang.framework.service.BaseService;
import com.baihang.project.ds.entity.DanYuanEntity;
import com.baihang.project.ds.entity.LouDongEntity;
import com.baihang.project.ds.entity.TaoXingEntity;
import com.baihang.project.ds.model.FangYuanModel;
import com.baihang.project.ds.model.TUserModel;

import redis.clients.jedis.Jedis;

/**
 * 通用服务层，里面都是共同的方法
 *
 */
@Service
public class CommonService extends BaseService{
	private static Logger logger = LoggerFactory.getLogger(CommonService.class);
	private Jedis jedis = RedisKit.getJedis();
	@Autowired
	private CommonDao dao;
	
	public List<LouDongEntity> getLouDong(){
		//List<FangYuanModel> model = dao.queryForFangYuanList("select r.*,b.D_BanName as banName from room as r left JOIN  Bans b on r.BanID =b.D_ID");
		List<FangYuanModel> model = dao.queryForFangYuanList("select * from room");
		logger.info("model="+model);
		//根据楼栋进行分组
		TreeMap<String,List<FangYuanModel>> louDongMap= model.stream().collect(Collectors.groupingBy(FangYuanModel::getD_BanName,TreeMap::new,Collectors.toList()));
		List<LouDongEntity>  loudonglist = new ArrayList<LouDongEntity>();//存放楼栋
		for (Entry<String, List<FangYuanModel>> entry : louDongMap.entrySet()) {
			LouDongEntity  louDongEty = new LouDongEntity();//1创建楼栋
			louDongEty.setName(entry.getKey());//楼栋名称
			List<FangYuanModel> danYuanModel = entry.getValue();//1-1 获取楼栋下的单元
			//根据列进行分组 决定顺序
			TreeMap<Integer, List<FangYuanModel>> columnMap = danYuanModel.stream().collect(Collectors.groupingBy(FangYuanModel::getD_column,TreeMap::new,Collectors.toList()));
			//根据单元进行分组
			TreeMap<String,List<FangYuanModel>> danYuanMap = danYuanModel.stream().collect(Collectors.groupingBy(FangYuanModel::getD_Unit,TreeMap::new,Collectors.toList()));
			List<DanYuanEntity>  danYuanList = new ArrayList<DanYuanEntity>();//存放单元
			Map<String, DanYuanEntity> DanYuanEntityMap = new HashMap<String, DanYuanEntity>();//记录单元
			for(Entry<Integer, List<FangYuanModel>> entryColumn:columnMap.entrySet()) {//取出一列
				List<FangYuanModel> columnList = entryColumn.getValue();//获得map中的值
				String dyName = columnList.get(0).getD_Unit();
				String txName = columnList.get(0).getD_position();
				for(Entry<String,List<FangYuanModel>> entryDanYuan:danYuanMap.entrySet()) {//取出一个单元
					if(dyName.equals(entryDanYuan.getKey())) {//判断列是否属于此单元
						if(DanYuanEntityMap.containsKey(entryDanYuan.getKey())) {
							DanYuanEntity danYuanEty =DanYuanEntityMap.get(entryDanYuan.getKey());
							List<TaoXingEntity> taoXingList = danYuanEty.getTaoxingList();//存放套型
							TaoXingEntity taoXingEty = new TaoXingEntity();//3创建套型
							taoXingEty.setColumnIndex(entryColumn.getKey());
							List<FangYuanModel> shiHaoModel =columnList;
							taoXingEty.setName(txName);
							taoXingEty.setShiHaoList(shiHaoModel);
							taoXingList.add(taoXingEty);//加入套型					
							danYuanEty.setTaoxingList(taoXingList);
						}else {
							DanYuanEntity danYuanEty = new DanYuanEntity();//2创建单元
							danYuanEty.setName(entryDanYuan.getKey());				
							List<TaoXingEntity> taoXingList = new ArrayList<TaoXingEntity>();//存放套型
							
							TaoXingEntity taoXingEty = new TaoXingEntity();//3创建套型
							taoXingEty.setColumnIndex(entryColumn.getKey());
							List<FangYuanModel> shiHaoModel =columnList;
							taoXingEty.setName(txName);
							
							taoXingEty.setShiHaoList(shiHaoModel);
							taoXingList.add(taoXingEty);//加入套型					
							danYuanEty.setTaoxingList(taoXingList);
							danYuanList.add(danYuanEty);	
							DanYuanEntityMap.put(entryDanYuan.getKey(), danYuanEty);//加入map
						}
					}else {
						continue;
					}
				}
			}				
			louDongEty.setDanyuanList(danYuanList);
			loudonglist.add(louDongEty);
		}
		return loudonglist;
	}
	
	/**
	 * @return
	 */
	private Object getD_BanName() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getRoomMsg(int id) {
		/*Record record = dao.queryForRecord(String.format("select r.*,t.* from room as r left JOIN  t_user t on r.D_Operation =t.D_Tel where r.D_ID=%d", id));
		String json = JsonKit.toJson(record);
		return json;*/
		
		Record record = new Record();
		String modelJson = jedis.hmget("rooms", String.valueOf(id)).get(0);
		FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});
		record.set("D_BanName", model.getD_BanName());
		record.set("D_Unit", model.getD_Unit());
		record.set("D_RoomNo", model.getD_RoomNo());
		record.set("D_FloorArea", model.getD_FloorArea());
		record.set("D_HouseModel", model.getD_HouseModel());
		record.set("D_RoomType", model.getD_RoomType());
		record.set("D_Price", model.getD_Price());
		record.set("D_Total", model.getD_Total());
		if(StrKit.isNotEmpty(model.getD_Operation())) {
			if(jedis.hexists("users", model.getD_Operation())) {
				String userJson = jedis.hmget("users", model.getD_Operation()).get(0);
				TUserModel  user = JSON.parseObject(userJson, new TypeReference<TUserModel>() {});
				record.set("D_Name", user.getD_Name());
				record.set("D_Tel", user.getD_Tel());
				record.set("D_Card", user.getD_Card());
			}
		}
		record.set("D_state", model.getD_state());
		record.set("D_Monitor", model.getD_Monitor());
		record.set("D_CollectionCount", model.getD_CollectionCount());
		record.set("E_CollectionCount", model.getE_CollectionCount());
		String json = JsonKit.toJson(record);
		return json;
		
	}
	
	
	public static void main(String[] args) {
		/*String jsonStr = "{\"studentName\":\"lily\",\"studentAge\":12}";
		JSONObject jsonObj = JSON.parseObject(jsonStr);
		System.err.println(jsonObj.getString("studentName"));*/
		String  JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";
		JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
		
		System.err.println(JSON.toJSONString(jsonArray.getJSONObject(0)));
		/* int size = jsonArray.size();
	        for (int i = 0; i < size; i++){
	            JSONObject jsonObject = jsonArray.getJSONObject(i);
	            //System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));
	        }*/
		} 
}
